package ink.ykb.redisLockDemo.config.lock.redis;

import java.net.UnknownHostException;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

	
	
	@Bean("redisTemplate")
	public RedisTemplate<String,Object> getRedisTemplate(RedisConnectionFactory connectionFactory) throws UnknownHostException{
		
		RedisTemplate<String,Object> template = new RedisTemplate<String,Object>();
		RedisSerializer<String> stringSerializer = new StringRedisSerializer();
		//解决应类加载器不同（RestartClassLoader）导致的转换类型异常
		ClassLoader loader = this.getClass().getClassLoader();
		JdkSerializationRedisSerializer jdkSerializer = new JdkSerializationRedisSerializer(loader);
		
		template.setConnectionFactory(connectionFactory);
		template.setDefaultSerializer(jdkSerializer);
		template.setKeySerializer(stringSerializer);
		template.setValueSerializer(jdkSerializer);
		template.setHashKeySerializer(stringSerializer);
		template.setHashValueSerializer(jdkSerializer);
		
		return template;
	}
	
	@Bean
	@Qualifier("lockRedisChannelListener")
	public MessageListenerAdapter getMessageListenerAdapter(){
		
		MessageListenerAdapter listenerAdapter = new MessageListenerAdapter(new LockRedisChannelListener());
		
		listenerAdapter.setSerializer(new StringRedisSerializer());
		
		return listenerAdapter;
	}
	
	@Bean
	public RedisMessageListenerContainer getRedisMessageListenerContainer(
			RedisConnectionFactory connectionFactory,
			@Qualifier("lockRedisChannelListener") MessageListenerAdapter lockRedisChannelListener
			){
		
		RedisMessageListenerContainer container = new RedisMessageListenerContainer();
		container.setConnectionFactory(connectionFactory);
		container.addMessageListener(lockRedisChannelListener,new PatternTopic(RedisLockAopConf.LOCK_PREFIX+"*"));//lock消息通知
		
		return container;
		
	}
	
}
